import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import datetime
import random
from influxdb import InfluxDBClient
from base_db import Influxdb_info
import search_db


def create_num(IP, PID, IDS, StartTime, Days, Hours, Minutes, Seconds, DataType, BaseNumber, Range, ifAdd, Step):
    # 【需填写】需要造数的开始时间， 有的需要考虑时区，则需要 - 8 小时作为开始时间
    strTime = StartTime + ' 00:00:00'
    # 【需填写】造数的基础数
    base = int(BaseNumber)
    # 【需填写】造数的浮动数
    random_num = int(Range)
    # 【需填写】数据采集时间间隔
    interval_hours = int(Hours)
    interval_mins = int(Minutes)
    interval_seconds = int(Seconds)
    # 【需填写】造数天数
    day = int(Days)

    # 【选填】是否递增  0 : 不递增， 1 ：递增
    ifAdd = int(ifAdd)
    # 【选填】递增步长， 默认递增1
    step = float(Step)
    # 【以下信息一般不需要修改了】

    # 检查数据格式
    time_valid = check_times(interval_seconds, interval_mins, interval_hours, day)
    if not time_valid:
        return
    if interval_hours < 0 or interval_mins < 0 or interval_seconds < 0 or day <= 0:
        print("间隔时间不能为负数,天数至少为一天")
        return
    else:
        interval_seconds = get_interval_seconds(interval_hours, interval_mins, interval_seconds)

    nums = day * 24 * 60 * 60 // interval_seconds
    db_info = Influxdb_info()
    influxDB_name = db_info.get_influxDB_name()
    influxDB_table = db_info.get_influxDB_table()
    password_db = db_info.get_influxDB_password()
    # 分段，每段写入数据值
    part_base_num = 120000

    # cd = create_data()
    # 需要造数的机器IP （也是数据库IP）
    influxDB_IP = IP
    # 工程 ID
    measurement_value = PID
    # 数据点对应 ids
    path_value = IDS
    # 连接数据库
    client = InfluxDBClient(influxDB_IP, 8086, influxDB_name, password_db, influxDB_table, ssl=True)
    # 显示数据库中表名
    # print(client.get_list_database())

    # 把strTime转化为时间格式,后面的秒位自动补位的
    startTime = datetime.datetime.strptime(strTime, "%Y-%m-%d %H:%M:%S")
    print("[INFO] 制造数据所在机器：" + influxDB_IP)
    print("[INFO] 开始时间：" + strTime)
    total_num = nums

    time_temp = startTime
    # 总造数分为几个段
    if nums % part_base_num:
        part_num = nums // part_base_num + 1
    else:
        part_num = nums // part_base_num
    # 第几段
    part_i = 1
    while nums:
        print("[INFO] 第 " + str(part_i) + "/" + str(part_num) + " 段")
        part_i += 1
        if nums > part_base_num:
            time_temp = add_influxDB(part_base_num, time_temp, interval_seconds, measurement_value, path_value, base,
                                     random_num, client, ifAdd, step, DataType)
            nums = nums - part_base_num
        else:
            time_temp = add_influxDB(nums, time_temp, interval_seconds, measurement_value, path_value, base, random_num,
                                     client, ifAdd, step, DataType)
            nums = 0

    print("[INFO] 总造数个数：" + str(total_num))
    search_db.search_data(measurement_value, path_value, client, influxDB_table)
    client.close()


def add_influxDB(num, time_temp, interval_seconds, measurement_value, path_value, base, random_num, client, ifadd, step,
                 DataType):
    print("    开始时间： " + time_temp.strftime("%Y-%m-%d %H:%M:%S"))
    print("    本段造数" + str(num))
    points = []
    for i in range(num):
        time1 = (time_temp + datetime.timedelta(seconds=interval_seconds * i)).strftime("%Y-%m-%d %H:%M:%S")
        if ifadd == 0:
            base_number = base + random.uniform(0, random_num)
        else:
            base_number = base + random.uniform(0, random_num) + i * step - 1
        points.append({
            'measurement': measurement_value,
            'tags': {
                'Path': path_value
            },
            'time': time1,
            'fields': {
                # 'integer': 90+random.randint(0,10)
                # 'float': base  + random.uniform(0, random_num)
                DataType: base_number
            }
        })
    client.write_points(points, database='scada')
    # 记录本段结束时造数时间
    time_temp = datetime.datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
    print("    结束时间： " + time_temp.strftime("%Y-%m-%d %H:%M:%S"))
    # 记录下一段开始时间
    time1 = (time_temp + datetime.timedelta(seconds=interval_seconds)).strftime("%Y-%m-%d %H:%M:%S")
    time_temp = datetime.datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
    # 返回下一段开始时间
    return time_temp


def get_interval_seconds(interval_hours, interval_mins, interval_seconds):
    fin_interval_seconds = interval_seconds + interval_mins * 60 + interval_hours * 3600
    return fin_interval_seconds


def check_times(interval_seconds, interval_mins, interval_hours, day):
    if isinstance(interval_seconds, int) and isinstance(interval_mins, int) and isinstance(interval_hours,
                                                                                           int) and isinstance(day,
                                                                                                               int):
        return True
    else:
        print("时间数据格式错误，请修改为int类型")
        return False
